
<template>
  <el-dialog v-model="ifShow" :title="modelTitle" width="1400" :before-close="handleCancel">
    <el-form ref="formRef" :model="formData" :rules="rules" label-width="auto" class="demo-ruleForm" status-icon>
      <el-row>
        <el-col :span="8">
          <el-form-item label="业务类型" prop="orderType">
            <el-select multiple clearable v-model="formData.orderType" placeholder="请选择">
              <el-option v-for="item in orderTypeArr" :key="item.value" :label="item.label" :value="item.value"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="平台" prop="platformId">
            <el-select multiple clearable v-model="formData.platformId" placeholder="请选择">
              <el-option v-for="item in platFormArr" :key="item.value" :label="item.label" :value="item.value"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="渠道" prop="channelId">
            <el-select multiple clearable v-model="formData.channelId" placeholder="请选择">
              <el-option v-for="item in channelArr" :key="item.value" :label="item.label" :value="item.value"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="城市" prop="cityId">
            <el-select filterable clearable v-model="formData.cityId" placeholder="请选择" @change="handleCityChange">
              <el-option v-for="item in cityOptions" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="车型" prop="vehicleTypeId">
            <el-select multiple filterable clearable v-model="formData.vehicleTypeId" placeholder="请选择">
              <el-option v-for="item in carTypeArr" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="是否上线" prop="status">
            <el-select v-model="formData.status" placeholder="请选择">
              <el-option :value="1" label="上线"></el-option>
              <el-option :value="0" label="下线"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="备注" prop="remark">
            <el-input placeholder="请输入" v-model="formData.remark"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8"></el-col>
        <el-col :span="8"></el-col>
        <h2>特殊时段加价</h2>
        <el-col :span="24" class="box">
          <el-form-item label="时段加价">
            <div class="flex_box" v-for="(item, i) in sdPriceArr" :key="item.id">
              <el-time-picker style="width: 200px" placeholder="请选择开始时间" v-model="item.start" value-format="HH:mm" format="HH:mm" />
              <el-time-picker style="width: 200px" placeholder="请选择结束时间" v-model="item.end" value-format="HH:mm" format="HH:mm" />
              <el-input :disabled="item.idx" style="width: 200px" placeholder="请输入百分比加价" v-model="item.percent">
                <template #append>%</template>
              </el-input>
              <el-input :disabled="item.idx" style="width: 200px" placeholder="请输入价格" v-model="item.price" suffix="元">
                <template #append>元</template>
              </el-input>
              <el-button type="danger" @click="handleRemove('sd', i, item)">删除</el-button>
              <el-button style="position: absolute; right: -80px" v-if="i == sdPriceArr.length - 1" type="primary" @click="handleAdd('sd')">新增</el-button>
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="24" class="box">
          <el-form-item label="急单价">
            <div class="flex_box" v-for="(item, i) in jdPriceArr" :key="item.id">
              <el-input :disabled="item.idx" placeholder="请输入多少分钟" v-model="item.time" suffix="分钟">
                <template #append>分钟</template>
              </el-input>
              <el-input :disabled="item.idx" placeholder="请输入价格" v-model="item.price" suffix="元">
                <template #append>元</template>
              </el-input>
              <el-button type="danger" @click="handleRemove('jd', i, item)">删除</el-button>
              <el-button style="position: absolute; right: -80px" v-if="i == jdPriceArr.length - 1" type="primary" @click="handleAdd('jd')">新增</el-button>
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="24" class="box">
          <el-form-item label="节假日价">
            <div class="flex_box" v-for="(item, i) in jjrPriceArr" :key="item.id">
              <el-date-picker
                showTime
                style="width: 200px"
                format="YYYY-MM-DD HH:mm"
                valueFormat="YYYY-MM-DD HH:mm:00"
                placeholder="请选择开始时间"
                v-model="item.start"
                :disabled="item.idx"
              />
              <el-date-picker
                :disabled="item.idx"
                showTime
                style="width: 200px"
                format="YYYY-MM-DD HH:mm"
                valueFormat="YYYY-MM-DD HH:mm:59"
                placeholder="请选择结束时间"
                v-model="item.end"
              />
              <el-input style="width: 200px" :disabled="item.idx" placeholder="请输入百分比加价" v-model="item.percent" suffix="%">
                <template #append>%</template>
              </el-input>
              <el-input style="width: 200px" :disabled="item.idx" placeholder="请输入价格" v-model="item.price" suffix="元">
                <template #append>元</template>
              </el-input>
              <el-button type="danger" @click="handleRemove('jjr', i, item)">删除</el-button>
              <el-button style="position: absolute; right: -80px" v-if="i == jjrPriceArr.length - 1" type="primary" @click="handleAdd('jjr')">新增</el-button>
            </div>
          </el-form-item>
        </el-col>
        <h2>围栏区域加价</h2>
        <el-col :span="24" class="box">
          <el-form-item label="围栏加价" style="position: relative">
            <div style="position: absolute; top: -180px; right: 20%; z-index: 999999">
              <Amap v-show="isShowMap" :isShowMap="isShowMap" :showPolygonData="showPolygonData"></Amap>
            </div>
            <div class="flex_box" v-for="(item, i) in wlPriceArr" :key="item.mathNum">
              <el-select style="width: 200px" filterable clearable v-model="item.polygonId" optionFilterProp="label" :disabled="item.idx">
                <el-option v-for="ele in polyOptions" :key="ele.id" :label="ele.desc" :value="ele.id">{{ ele.desc }}</el-option>
              </el-select>
              <el-button :disabled="item.idx" type="primary" @click="handleLook(item)" style="margin-right: 6px">围栏预览</el-button>
              <el-input style="width: 200px" :disabled="item.idx" placeholder="请输入加价比例" v-model="item.percent" suffix="%">
                <template #append>%</template>
              </el-input>
              <el-input style="width: 200px" :disabled="item.idx" placeholder="请输入价格" v-model="item.price" suffix="元">
                <template #append>元</template>
              </el-input>
              <el-button type="danger" @click="handleRemove('wl', i, item)">删除</el-button>
              <el-button style="position: absolute; right: -80px" v-if="i == wlPriceArr.length - 1" type="primary" @click="handleAdd('wl')">新增</el-button>
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="24" class="box">
          <el-form-item label="区域加价">
            <div class="flex_box" v-for="(item, i) in qyPriceArr" :key="item.mathNum">
              <el-select style="width: 140px" filterable clearable @change="handleProvinceChange($event, i)" v-model="item.province" optionFilterProp="label" :disabled="item.idx">
                <el-option v-for="ele in provinceOptions" :key="ele.id" :label="ele.name" :value="ele.name">{{ ele.name }}</el-option>
              </el-select>
              <el-select style="width: 140px" filterable clearable @change="handleCityChange2($event, i)" v-model="item.cityName" optionFilterProp="label" :disabled="item.idx">
                <el-option v-for="ele in cityOptions2" :key="ele.id" :label="ele.name" :value="ele.name">{{ ele.name }}</el-option>
              </el-select>
              <el-select style="width: 140px" filterable clearable v-model="item.district" optionFilterProp="label" :disabled="item.idx">
                <el-option v-for="ele in areaOptions" :key="ele.id" :label="ele.name" :value="ele.name">{{ ele.name }}</el-option>
              </el-select>

              <el-input style="width: 140px" :disabled="item.idx" placeholder="请输入加价比例" v-model="item.percent" suffix="%">
                <template #append>%</template>
              </el-input>
              <el-input style="width: 140px" :disabled="item.idx" placeholder="请输入价格" v-model="item.price" suffix="元">
                <template #append>元</template>
              </el-input>
              <el-button type="danger" @click="handleRemove('qy', i, item)">删除</el-button>
              <el-button style="position: absolute; right: -80px" v-if="i == qyPriceArr.length - 1" type="primary" @click="handleAdd('qy')">新增</el-button>
            </div>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleOk">确认</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import CommonApi from "@/api/common";
import JntApi from "@/api/jnt";
import { ref, onMounted, reactive, nextTick } from "vue";
import Amap from "@/components/Amap/map.vue";
import { channelArr, bizTypeArr, orderTypeArr, platFormArr, carTypeArr } from "@/enums/common";
const carOptions = ref();
const polyOptions = ref();
const provinceOptions = ref(); //省份
const cityOptions2 = ref(); //城市
const areaOptions = ref(); //区域
const showPolygonData = ref(); //围栏数据
const isShowMap = ref(false); //围栏
const props = defineProps<{}>();
const emit = defineEmits(["success"]);
const formRef: any = ref(null);
let formData: any = ref({
  id: "",
  remark: undefined,
  status: undefined,
  orderType: undefined,
  platformId: undefined,
  channelId: undefined,
  cityId: undefined,
  cityName: "",
  vehicleTypeId: undefined,
  periodPrice: [],
  urgentPrice: [],
  holidayPrice: [],
  polygonPrice: [], //围栏
});
const rules = reactive({
  orderType: [{ required: true, message: "请输入类型 1.接机 2.送机 3.接站 4.送站 5.包车 6.预约用车 7.实时打车!" }],
  platformId: [{ required: true, message: "请输入平台id!" }],
  channelId: [{ required: true, message: "请输入渠道id 1.携程 2.飞猪 3.南航 4.航旅!" }],
  cityId: [{ required: true, message: "请输入城市ID!" }],
  cityName: [{ required: true, message: "请输入城市名称!" }],
  vehicleTypeId: [{ required: true, message: "请输入车型id!" }],
  status: [{ required: true, message: "请选择!" }],
});
const sdPriceArr: any = ref([{ start: "", end: "", percent: "100", price: "0", id: Date.now() + Math.random().toString(16).slice(2) }]); //里程价
const jdPriceArr: any = ref([{ price: "0", time: "", id: Date.now() + Math.random().toString(16).slice(2) }]); //里程价
const jjrPriceArr: any = ref([{ price: "0", start: "", end: "", percent: "100", id: Date.now() + Math.random().toString(16).slice(2) }]); //里程价
const wlPriceArr: any = ref([{ polygonId: "", percent: "100", price: "0", mathNum: Date.now() + Math.random().toString(16).slice(2) }]); //里程价
const qyPriceArr: any = ref([{ province: "", cityName: "", district: "", percent: "100", price: "0", mathNum: Date.now() + Math.random().toString(16).slice(2) }]); //区域加价
const ifShow = ref(false);
const modelTitle = ref();
const cityOptions = ref();

//点击省份下拉触发
function handleProvinceChange(value, index) {
  cityOptions2.value = areaOptions.value = null;
  qyPriceArr.value[index].cityName = undefined;
  qyPriceArr.value[index].district = undefined;
  CommonApi.getAreaList({ parentId: provinceOptions.value.find((item) => item.name == value).id }).then((res) => (cityOptions2.value = res.result));
}
//点击城市下拉触发
function handleCityChange2(value, index) {
  areaOptions.value = null;
  qyPriceArr.value[index].district = undefined;
  CommonApi.getAreaList({ parentId: cityOptions2.value.find((item) => item.name == value).id }).then((res) => (areaOptions.value = res.result));
}

//点击围栏预览触发
function handleLook(data: any) {
  showPolygonData.value = null;
  showPolygonData.value = polyOptions.value.find((item) => item.id === data.polygonId).points;
  showPolygonData.value = showPolygonData.value.map((item) => item.split(",").map(Number));
  isShowMap.value = !isShowMap.value;
}

function handleRemove(code: any, index: any, row: any) {
  if (row.idx) {
    // createMessage.error("请去一键加价删除");
    return;
  }

  if (code == "sd") {
    if (sdPriceArr.value.length !== 1) {
      sdPriceArr.value.splice(index, 1);
    }
  } else if (code == "jd") {
    if (jdPriceArr.value.length !== 1) {
      jdPriceArr.value.splice(index, 1);
    }
  } else if (code == "jjr") {
    if (jjrPriceArr.value.length !== 1) {
      jjrPriceArr.value.splice(index, 1);
    }
  } else if (code == "wl") {
    if (wlPriceArr.value.length !== 1) {
      wlPriceArr.value.splice(index, 1);
    }
  } else if (code == "qy") {
    if (qyPriceArr.value.length !== 1) {
      qyPriceArr.value.splice(index, 1);
    }
  }
}
function handleAdd(code: any) {
  if (code == "sd") {
    sdPriceArr.value.push({ start: "", end: "", percent: "100", price: "0", id: Date.now() + Math.random().toString(16).slice(2) });
  } else if (code == "jd") {
    jdPriceArr.value.push({ price: "0", time: "", id: Date.now() + Math.random().toString(16).slice(2) });
  } else if (code == "jjr") {
    jjrPriceArr.value.push({ price: "0", start: "", end: "", percent: "100", id: Date.now() + Math.random().toString(16).slice(2) });
  } else if (code == "wl") {
    wlPriceArr.value.push({ polygonId: "", percent: "100", price: "0", mathNum: Date.now() + Math.random().toString(16).slice(2) });
  } else if (code == "qy") {
    qyPriceArr.value.push({
      province: "",
      cityName: "",
      district: "",
      percent: "100",
      price: "0",
      mathNum: Date.now() + Math.random().toString(16).slice(2),
    });
  }
}

function edit(title: any, row: any) {
  nextTick(() => {
    modelTitle.value = title;
    ifShow.value = true;
    if (formRef.value) {
      formRef.value.resetFields();
    }
    if (title == "新增") {
      formData.value = {
        id: "",
        remark: undefined,
        status: undefined,
        orderType: undefined,
        platformId: undefined,
        channelId: undefined,
        cityId: undefined,
        cityName: "",
        vehicleTypeId: undefined,
        periodPrice: [],
        urgentPrice: [],
        holidayPrice: [],
        polygonPrice: [], //围栏
      };
    }

    if (row && row.id) {
      // 里程价格
      let { areaPrice, periodPrice, urgentPrice, polygonPrice, holidayPrice } = row;
      if (periodPrice.length) {
        sdPriceArr.value = JSON.parse(JSON.stringify(periodPrice));
      }

      if (urgentPrice.length) {
        jdPriceArr.value = JSON.parse(JSON.stringify(urgentPrice));
      }

      if (polygonPrice.length) {
        wlPriceArr.value = JSON.parse(JSON.stringify(polygonPrice));
      }

      if (holidayPrice.length) {
        jjrPriceArr.value = JSON.parse(JSON.stringify(holidayPrice));
      }
      if (areaPrice.length) {
        qyPriceArr.value = JSON.parse(JSON.stringify(areaPrice));
      }
      //赋值
      if (!Array.isArray(row.channelId)) {
        row.channelId = [row.channelId];
      }
      if (!Array.isArray(row.platformId)) {
        row.platformId = [row.platformId];
      }
      if (!Array.isArray(row.vehicleTypeId)) {
        row.vehicleTypeId = [row.vehicleTypeId];
      }
    }
    Object.assign(formData.value, row);
  });
}

/**
 * 确定按钮点击事件
 */
async function handleOk() {
  await formRef.value.validate((valid: any, fields: any) => {
    if (valid) {
      let model: any = formData.value;
      model.periodPrice = sdPriceArr.value;
      model.urgentPrice = jdPriceArr.value;
      model.holidayPrice = jjrPriceArr.value;
      model.polygonPrice = wlPriceArr.value;
      model.areaPrice = qyPriceArr.value;
      JntApi.productEdits(model).then((res: any) => {
        if (res.code == 0) {
          ElMessage.success(res.message);
          formRef.value.resetFields();
          emit("success");
          handleCancel();
        }
      });
    } else {
      console.log("error submit!", fields);
    }
  });
}

//城市下拉框点击事件
function handleCityChange(value: any) {
  formData.value.cityName = cityOptions.value.find((item: any) => item.id == value).name;
}

/**
 * 取消按钮回调事件
 */
function handleCancel() {
  ifShow.value = false;
  formRef.value.resetFields();
  sdPriceArr.value = [{ start: "", end: "", percent: "100", price: "0", id: Date.now() + Math.random().toString(16).slice(2) }];
  jdPriceArr.value = [{ price: "0", time: "", id: Date.now() + Math.random().toString(16).slice(2) }];
  jjrPriceArr.value = [{ price: "0", start: "", end: "", percent: "100", id: Date.now() + Math.random().toString(16).slice(2) }];
  wlPriceArr.value = [{ polygonId: "", percent: "100", price: "0", mathNum: Date.now() + Math.random().toString(16).slice(2) }];
  qyPriceArr.value = [{ province: "", cityName: "", district: "", percent: "100", price: "0", mathNum: Date.now() + Math.random().toString(16).slice(2) }];
  isShowMap.value = false;
  cityOptions2.value = null;
  areaOptions.value = null;
}

defineExpose({
  edit,
});
onMounted(() => {
  CommonApi.getCity({ pageNo: 1, pageSize: 99999 }).then((res) => {
    cityOptions.value = res.result;
  });
  //查询围栏
  JntApi.getPolygonList({
    pageNo: 1,
    pageSize: 9999,
  }).then((res) => {
    polyOptions.value = res.result;
  });

  CommonApi.getAreaList({ parentId: 0 }).then((res) => {
    provinceOptions.value = res.result;
  });
});
</script>
<style lang="scss" scoped>
.flex_box {
  display: flex;
  margin-bottom: 14px;
  position: relative;
  ::v-deep .el-input {
    width: 100%;
    margin: 0 14px;
  }
}
</style>
